package com.guojian.http.handle.route;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.smartboot.http.utils.AntPathMatcher;

import com.guojian.http.handle.AbstractJettyHandler;
import com.guojian.http.handle.config.RouteConfig;
import com.guojian.http.handle.service.HttpJettyHttpclientServiceHandle;

/**
 * URL路由器,根据输入的URL,自动匹配相应的转发路径
 * 
 * 具体地址配置在 @RouteConfig
 * 
 * @author guoJian
 *
 */
public class HttpJettyRouteHandle extends AbstractHandler {

	private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

	private HttpJettyHttpclientServiceHandle serviceHandle = new HttpJettyHttpclientServiceHandle();

	private HttpJetty404Handle default404Handle = new HttpJetty404Handle();

	@Override
	public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String requestUri = target;

		AbstractJettyHandler defaultJettyHandle = default404Handle;

		for (Map.Entry<String, String> entity : RouteConfig.getRoutePatternUrl().entrySet()) {
			if (PATH_MATCHER.match(entity.getKey(), requestUri)) {
				String uriPath = PATH_MATCHER.extractPathWithinPattern(entity.getKey(), requestUri);//:: /**匹配的URL
				defaultJettyHandle = serviceHandle.setTargetUrl(entity.getValue() + uriPath);
				//找到第一个匹配的URL
				break;
			}
		}

		defaultJettyHandle.handle(target, baseRequest, request, response);

	}

}
